import {
  Controller,
  Post,
  Body,
  Get,
  Put,
  Param,
  ParseIntPipe,
  Delete,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { CommonObjectProps, CommonResponse } from '../typings';
import { responseWrapper } from '../utils';

@Controller('posts')
export class PostsController {
  constructor(private readonly postService: PostsService) {}

  @Post()
  async addPost(@Body() post: CommonObjectProps): Promise<CommonResponse> {
    try {
      const res = await this.postService.addPost(post);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async posts(): Promise<CommonResponse> {
    try {
      const res = await this.postService.posts();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getPost(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.postService.getPost(id);
      if (!res) throw new Error('帖子不存在');
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Put(':id')
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: CommonObjectProps,
  ): Promise<CommonResponse> {
    try {
      const res = await this.postService.update(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async delete(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.postService.delete(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
